package com.yang.servlet;

import com.google.gson.Gson;
import com.yang.pojo.Manager;
import com.yang.service.ManagerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/Manager2ListServlet")
public class Manager2ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ManagerService managerService = new ManagerService();
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        try {
            ArrayList<Manager> managers = managerService.findManagerByRoleId(roleId);

            //将managers的数据用json格式响应给页面
            Gson gson = new Gson();
            String toJson = gson.toJson(managers);

            response.setContentType("application/json;charset=utf-8");

            //在servlet中通过输出流响应ajax
            PrintWriter writer = response.getWriter();
            writer.println(toJson);
            writer.flush();
            writer.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
